package com.csf.service.impl;

import com.csf.dao.CommentMapper;
import com.csf.dao.DiscussPostMapper;
import com.csf.entity.Comment;
import com.csf.service.CommentService;
import com.csf.service.DiscussPostService;
import com.csf.util.CommunityActivation;
import com.csf.util.MGWordFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.util.HtmlUtils;

import java.util.List;

@Service
public class CommentServiceImpl implements CommentService, CommunityActivation {

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private MGWordFilter mgWordFilter;

    @Autowired
    private DiscussPostService discussPostMapper;

    @Override
    public List<Comment> findCommentList(int entityType, int entityId, int iniRows, int limit) {
        return commentMapper.findCommentList(entityType,entityId,iniRows,limit);
    }

    @Override
    public int findCommentCount(int entityType, int entityId) {
        return commentMapper.findCommentCount(entityType, entityId);
    }

    @Override
    public int insertComment(Comment comment) {
        if (comment == null){
            throw new IllegalArgumentException("评论内容不能为空");
        }
//    敏感字符和前端代码过滤
        String escape = HtmlUtils.htmlEscape(comment.getContent());
        comment.setContent(escape);
        comment.setContent(mgWordFilter.filter(comment.getContent()));

//    过滤完成后对将评论添加
        int insertComment = commentMapper.insertComment(comment);

//       添加的同时需要将帖子列表中的评论数据进行更新(由于有两张数据库表同时间段操作，所以我们假如事务，当出现错误时及时回滚)
        if (comment.getEntityType() == ENTITY_TYPE_POST){
            int count = commentMapper.findCommentCount(ENTITY_TYPE_POST, comment.getEntityId());
            discussPostMapper.updateDisCount(comment.getEntityId(),count);
        }
        return insertComment;
    }

    @Override
    public Comment selectCommentById(int id) {
        return commentMapper.selectCommentById(id);
    }
}
